package plat

import (
	"bytes"
	"encoding/json"
	"fmt"
	"strconv"
	"strings"
	"time"

	"github.com/PuerkitoBio/goquery"
	"publish/app/account/model"
	"encoding/hex"
	"crypto/md5"
)

func init() {
	RegisterPlat("DAYU", newplat_dayu())
}

type platdayu struct {
	*plathttp
}

func newplat_dayu() Plat {
	return &platdayu{plathttp: &plathttp{
		Host: "",
	}}
}

func (p *platdayu) GetProfit(account *model.Account, start, end time.Time) ([]AccountProfit, error) {
	beginTime := start.Format("20060102")
	endTime := end.Format("20060102")

	url := fmt.Sprintf(`https://mp.dayu.com/dashboard/feature/profit/profit_day?beginDate=%s&endDate=%s`, beginTime, endTime)

	p.setCookie(account.GetCookie())
	bytesBody, err := p.getReq(url)
	if err != nil {
		return nil, err
	}

	profits := DatyProfits{}
	err = json.Unmarshal(bytesBody, &profits)
	if err != nil {
		return nil, err
	}

	rets := make([]AccountProfit, 0)
	for _, profit := range profits.Data {
		t, err := time.Parse("20060102", strconv.FormatInt(profit.Data, 10))
		if err != nil {
			continue
		}
		rets = append(rets, AccountProfit{
			AccountId: account.Id,
			Profit:    profit.Profit,
			Time:      time.Now().Format("2006-01-02 15:04:05"),
			Date:      t.Format("2006-01-02"),
		})
	}

	return rets, nil
}

func (p *platdayu) GetIndex(account *model.Account, start, end time.Time) ([]AccountData, error) {

	beginTime := start.Format("20060102")
	endTime := end.Format("20060102")

	url := fmt.Sprintf(`https://mp.dayu.com/dashboard/feature/star/starinfo?beginDate=%s&endDate=%s`, beginTime, endTime)

	p.setCookie(account.GetCookie())
	bytesBody, err := p.getReq(url)
	if err != nil {
		return nil, err
	}

	index := DayuIndexs{}
	err = json.Unmarshal(bytesBody, &index)
	if err != nil {
		return nil, err
	}

	rets := make([]AccountData, 0)
	for _, index := range index.Data {
		rets = append(rets, AccountData{
			AccountId: account.Id,
			Index:     strconv.FormatFloat(index.Score, 'f', 2, 64),
			Time:      time.Now().Format("2006-01-02 15:04:05"),
			Date:      strings.TrimSpace(index.CreateTime[:10]),
			IndexJson: map[string]interface{}{
				"original": index.OriginalScore,
				"domain":   index.VerScore,
				"interest": index.UserScore,
				"active":   index.ActivityScore,
				"quality":  index.HealthScore,
			},
		})
	}

	return rets, nil
}

func (p *platdayu) GetStatistic(account *model.Account, start, end time.Time) ([]AccountStatisttic, error) {
	datas := []AccountStatisttic{}

	articles, _ := p.GetArticleStatistic(account, start, end)
	datas = append(datas, articles...)
	videos, _ := p.GetVideoStatistic(account, start, end)
	datas = append(datas, videos...)
	albums, _ := p.GetPictureStatistic(account, start, end)
	datas = append(datas, albums...)

	return datas, nil
}

func (p *platdayu) GetEveryStatistic(account *model.Account,start,end time.Time)([]EveryDayStatisttic, error){
	return nil,nil
}


func (p *platdayu) GetArticleStatistic(account *model.Account, start, end time.Time) ([]AccountStatisttic, error) {
	url := fmt.Sprintf(`https://mp.dayu.com/api/stat/article/all/daylist?beginDate=%s&endDate=%s&origin=manual&_=1513154526966`, start.Format(`2006-01-02`), end.Format(`2006-01-02`))

	p.setCookie(account.GetCookie())
	bytesBody, err := p.getReq(url)
	if err != nil {
		return []AccountStatisttic{}, err
	}

	index := DayuStatistics{}
	err = json.Unmarshal(bytesBody, &index)
	if err != nil {
		return []AccountStatisttic{}, err
	}

	datas := []AccountStatisttic{}
	for _, data := range index.Data.List {
		datas = append(datas, AccountStatisttic{
			AccountId: account.Id,
			Num:       data.ReadCount, //阅读量
			Type:      "reads_news",
			Time:      time.Now().Format("2006-01-02 15:04:05"),
			Date:      data.Data,
		}, AccountStatisttic{
			AccountId: account.Id,
			Num:       data.RecommendCount, //推荐量
			Type:      "recommends_news",
			Time:      time.Now().Format("2006-01-02 15:04:05"),
			Date:      data.Data,
		})
	}

	return datas, nil
}

func (p *platdayu) GetVideoStatistic(account *model.Account, start, end time.Time) ([]AccountStatisttic, error) {
	url := fmt.Sprintf(`https://mp.dayu.com/api/stat/video/play/daylist?beginDate=%s&endDate=%s&source=uc&origin=manual&_=1513155366625`, start.Format(`2006-01-02`), end.Format(`2006-01-02`))

	p.setCookie(account.GetCookie())
	bytesBody, err := p.getReq(url)
	if err != nil {
		return []AccountStatisttic{}, err
	}

	index := DayuStatisticsVideo{}
	err = json.Unmarshal(bytesBody, &index)
	if err != nil {
		return []AccountStatisttic{}, err
	}

	datas := []AccountStatisttic{}
	for _, data := range index.Data.List {
		datas = append(datas, AccountStatisttic{
			AccountId: account.Id,
			Num:       data.ReadCount, //观看次数
			Type:      "reads_video",
			Time:      time.Now().Format("2006-01-02 15:04:05"),
			Date:      data.Data,
		})
	}

	return datas, nil
}

func (p *platdayu) GetPictureStatistic(account *model.Account, start, end time.Time) ([]AccountStatisttic, error) {
	url := fmt.Sprintf(`https://mp.dayu.com/api/stat/album/content/daylist?beginDate=%s&endDate=%s&_=1513155649928`, start.Format(`2006-01-02`), end.Format(`2006-01-02`))

	p.setCookie(account.GetCookie())
	bytesBody, err := p.getReq(url)
	if err != nil {
		return []AccountStatisttic{}, err
	}

	index := DayuStatistics{}
	err = json.Unmarshal(bytesBody, &index)
	if err != nil {
		return []AccountStatisttic{}, err
	}

	datas := []AccountStatisttic{}
	for _, data := range index.Data.List {
		datas = append(datas, AccountStatisttic{
			AccountId: account.Id,
			Num:       data.ReadCount, //阅读量
			Type:      "reads_gallery",
			Time:      time.Now().Format("2006-01-02 15:04:05"),
			Date:      data.Data,
		}, AccountStatisttic{
			AccountId: account.Id,
			Num:       data.RecommendCount, //推荐量
			Type:      "recommends_gallery",
			Time:      time.Now().Format("2006-01-02 15:04:05"),
			Date:      data.Data,
		})
	}

	return datas, nil
}

func (p *platdayu) GetLevel(account *model.Account) (string, error) {

	url := `https://mp.dayu.com/dashboard/index`
	plat := newtoutiao(account.GetCookie())
	bodyBytes, err := plat.getReq(url)
	if err != nil {
		return "", err
	}
	// 未登录
	if strings.Contains(string(bodyBytes), "location.href =") {
		return "", nil
	}
	doc, err := goquery.NewDocumentFromReader(bytes.NewReader(bodyBytes))
	if err != nil {
		return "", err
	}
	level := doc.Find("#w-menu-feature_ad span").Text()
	if strings.Contains(level, "广告分成") {
		return LEVEL_MONEY, nil
	}

	return LEVEL_NEW, nil
}

func (p *platdayu) GetArticles(account *model.Account, start time.Time, end time.Time) ([]Article, error) {
	articles := []Article{}
	page := 1

	for {
		api := fmt.Sprintf(`https://mp.dayu.com/api/stat/article/detail/articlelist?beginDate=%s&endDate=%s&origin=manual&page=%d`, start.Format(`2006-01-02`), end.Format(`2006-01-02`), page)
		plat := newtoutiao(account.GetCookie())
		bodyBytes, err := plat.getReq(api)
		if err != nil {
			return nil, err
		}

		datas := DatyArticleList{}
		if err := json.Unmarshal(bodyBytes, &datas); err != nil {
			return nil, err
		}

		if len(datas.Data) == 0 {
			break
		}

		for _, data := range datas.Data {
			statusMsg := "未知"
			status := 0
			t, _ := time.Parse("2006-01-02 15:04:05", data.Time)

			if t.Before(start) {
				break
			}

			if t.Before(end) {
				articles = append(articles, Article{
					ArticleId: MD5(data.Title+data.Time),
					Title:   data.Title,
					Url:     `https://mparticle.uc.cn/article.html?wm_aid=`+data.Aid,
					Time:    t,
					Status:  status,
					FailMsg: statusMsg,

					RecommentCount : data.RecommentCount,
					ReadCount: data.ReadCount,
					CommentCount: data.CommentCount,
					FavCount: data.FavCount,
				})
			}
		}

		page++
	}

	api := fmt.Sprintf(`https://mp.dayu.com/api/stat/article/getManualRealtimeArticle`)
	plat := newtoutiao(account.GetCookie())
	bodyBytes, err := plat.getReq(api)
	if err != nil {
		return nil, err
	}
	realData := DayuRealList{}
	if err := json.Unmarshal(bodyBytes, &realData); err != nil {
		return nil, err
	}

	for _,realArticle := range realData.ArticleList{
		isExist := false
		for j,article := range articles{
			if realArticle.Title == article.Title{
				articles[j].ReadCount = realArticle.ReadCount
				isExist = true
				break
			}
		}

		if (!isExist){
			t, _ := time.Parse("2006-01-02 15:04:05", realArticle.Time)
			articles = append(articles, Article{
				ArticleId: MD5(realArticle.Title+realArticle.Time),
				Title:   realArticle.Title,
				Url:     "",
				Time:    t,
				Status:  0,
				FailMsg: "未知",

				RecommentCount : -1,
				ReadCount: realArticle.ReadCount,
				CommentCount: -1,
				FavCount: -1,
			})
		}
	}

	return articles, nil
}

func MD5(text string) string {
	md5Ctx := md5.New()
	md5Ctx.Write([]byte(text))
	cipherStr := md5Ctx.Sum(nil)
	return hex.EncodeToString(cipherStr)
}

func (p *platdayu) GetPayRecord(account *model.Account, start time.Time, end time.Time) ([]PayRecord, error) {
	return nil, nil
}
func (p *platdayu) GetFinancialInformation(account *model.Account) (*FinancialInformation, error) {

	return nil, nil
}
